<?php

namespace Action\Contact;

class Answer extends \Library\Action\UserAction
	implements \Library\Action\AjaxAction {

	private $_contact;

	public function execute() {
		parent::execute();
		
		$request_id = (int) $this->getParam( 'id' );
		$answer = trim($this->getParam( 'answer' ) );
		
		$request = \Bean\User\Request::get( $request_id );
		
		if( !$request->getAcceptor()->isMe() ) {
			throw new \Exception( 'This request doesn\'t concern you' );
		}
		
		switch( $answer ) {
			case 'yes' :
				$request->accept();
				return array( 'answer' => 'yes' );
				break;
			case 'no' :
				$request->refuse();
				return array( 'answer' => 'no' );
				break;
				
			default:
				throw new \Exception( 'Unknown answer' );
		}
		
			

		$n = _q()->getC( 'users_requests', array(
			'requester_id' => _u()->getUserId(),
			'acceptor_id' => $user_id
		) );
		
		$n += _q()->getC( 'users_requests', array(
			'acceptor_id' => _u()->getUserId(),
			'requester_id' => $user_id
		) );
		
		if( $n ) {
			throw new \Exception( 'Request already done' );
		}
		
		_q()->set1( 'users_requests', array(
			'requester_id' => _u()->getUserId(),
			'acceptor_id' => $user_id,
			'request_time' => _now(),
			'message' => $message ? $message : null
		) );
		
		return true;
	}
	
}
